package com.ppch.wuwamanus.tools;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.util.List;

/**
 * Package:image-search-mcp
 * ClassName:ImageSearchTool
 *
 * @Author 泡泡茶壶
 * @Create 2025/7/25 22:10
 * @Version 1.0
 * Description:
 *  图片搜索工具：使用 Pexels API 实现图片搜索
 */
public class ImageSearchTool {

    private String API_URL = "https://api.pexels.com/v1/search?query=";

    private String API_KEY;

    public ImageSearchTool(String API_KEY) {
        this.API_KEY = API_KEY;
    }

    @Tool(description = "根据关键词搜索对应的图片")
    public String searchImageByKerWord(@ToolParam(description = "搜索关键词") String query) {
        // 构建API请求URL
        String apiUrl = API_URL + query;
        try {
            // 发送HTTP GET请求
            HttpResponse response = HttpRequest.get(apiUrl)
                    .header("Authorization", API_KEY)
                    .execute();
            // 检查响应状态
            if (!response.isOk()) {
                throw new RuntimeException("API请求失败: " + response.getStatus());
            }
            // 解析JSON响应
            JSONObject json = JSONUtil.parseObj(response.body());
            JSONArray photos = json.getJSONArray("photos");
            // 提取所有图片URL
            List<String> imageUrls = photos.stream()
                    .map(photoObj -> (JSONObject) photoObj)
                    .map(photo -> photo.getJSONObject("src"))
                    .map(photo -> photo.getStr("original"))
                    .toList();
            //使用逗号将每一个图片URL地址进行连接，最终得到一个字符串
            return String.join(",",imageUrls);
        } catch (Exception e) {
            throw new RuntimeException("获取图片失败: " + e.getMessage(), e);
        }
    }
}
